import React, { Component, PropTypes } from 'react'
import { Button, Col, Form, Icon, Input, message, Modal, Popconfirm, Select, Table, Tag } from 'antd'
import { fetchPost } from '../../../utils/request'
import Style from './Index.less'

const FormItem = Form.Item

const EditableCell = ({ editable, value, onChange }) => (
  <div>
    {editable
      ? <Input style={{ margin: '-5px 0' }} value={value} onChange={e => onChange(e.target.value)}/>
      : value
    }
  </div>
)

class Index extends React.Component {

  constructor (props) {
    super(props)
    this.state = {
      visible: false,
      auditorList: [],
      page: {
        currentPage: 1,
        pageSize: 30,
        totalCount: 0
      },
      loading: false,
      adminList: []
    }

  }

  componentDidMount () {
    this.getAuditorData()
    this.getData()
  }

  componentWillReceiveProps (props) {

  }

  getAuditorData () {
    fetchPost('/audit/auditor/common/list').then((res) => {
      if (res.code === 0) {
        if (res.data !== null) {
          this.setState({
            adminList: res.data.adminList,
          })
        }
      } else {
        message.error(res.msg)
      }
    })
  }

  // 获取表格数据
  getData () {
    this.setState({
      loading: true
    })
    fetchPost(`/audit/auditor/list?currentPage=${this.state.page.currentPage}&pageSize=${this.state.page.pageSize}`).then((res) => {
      if (res.code === 0) {
        if (res.data !== null) {
          this.setState({
            auditorList: res.data.auditorList,
            page: res.page,
          }, () => {
            this.cacheData = this.state.auditorList.map(item => ({ ...item }))
          })
        }
      } else {
        message.error(res.msg)
      }
    })
    this.setState({
      loading: false
    })
  }

  // 保存配置
  saveConfig (params) {
    const { adminId, adminName, baseOrderNum, dailyManualOrderNum } = params
    let params2 = {
      adminId,
      adminName,
      baseOrderNum,
      dailyManualOrderNum
    }
    fetchPost('/audit/auditor/orderNum/save', params2).then((res) => {
      if (res.code === 0) {
        message.info(res.msg)
      } else {
        message.error(res.msg)
      }
      this.getData()
    })
  }

  renderColumns (text, record, column) {
    return (
      <EditableCell
        editable={record.editable}
        value={text}
        onChange={value => this.handleChange(value, record.key, column)}
      />
    )
  }

  handleChange (value, key, column) {
    const newData = [...this.state.auditorList]
    const target = newData.filter(item => key === item.key)[0]
    if (target) {
      target[column] = value
      this.setState({
        auditorList: newData
      })
    }
  }

  edit (key) {
    const newData = [...this.state.auditorList]
    const target = newData.filter(item => key === item.key)[0]
    if (target) {
      target.editable = true
      this.setState({
        auditorList: newData
      })
    }
  }

  save (key) {
    const newData = [...this.state.auditorList]
    const target = newData.filter(item => key === item.key)[0]
    if (target) {
      delete target.editable
      console.log(target)
      this.saveConfig(target)
      this.setState({
        auditorList: newData
      })
      this.cacheData = newData.map(item => ({ ...item }))
    }
  }

  cancel (key) {
    const newData = [...this.state.auditorList]
    const target = newData.filter(item => key === item.key)[0]
    if (target) {
      Object.assign(target, this.cacheData.filter(item => key === item.key)[0])
      delete target.editable
      this.setState({
        auditorList: newData
      })
    }
  }

  showModal = (e) => {
    this.setState({
      visible: true
    })
  }

  currentPage (current) {
    this.setState({
      page: {
        ...this.state.page,
        currentPage: current
      }
    }, () => {
      this.getData()
    })
  }

  setPagination () {
    let self = this
    return {
      total: this.state.page.totalCount,
      pageSize: this.state.page.pageSize,
      showSizeChanger: false,
      showQuickJumper: true,
      showTotal (total) {
        return `Total ${total} `
      },
      onChange (current) {
        self.setState({
          page: {
            ...self.state.page,
            current
          }
        }, () => {
          self.currentPage(current)
        })
      }
    }
  }

  handleOk = (e) => {
    let self = this
    this.props.form.validateFields((error, values) => {
      if (!error) {
        let params = {
          adminName: values.name,
          mobile: values.mobile,
          baseOrderNum: values.baseOrderNum
        }
        fetchPost('/audit/auditor/save/v2', params).then((res) => {
          if (res.code === 0) {
            message.info(res.msg, 0.2, () => {
              this.setState({
                visible: false,
              }, () => {
                this.getData()
              })
            })
            this.props.form.resetFields()
          } else {
            message.error(res.msg)
          }
        })
      }
    })
  }

  handleCancel = (e) => {
    this.setState({
      visible: false,
    }, () => {

    })
    this.props.form.resetFields()
  }

  forbiddenAdmin (record) {
    fetchPost(`/audit/auditor/status/save`, { status: 1, adminId: record.adminId }).then(res => {
      if (res.code === 0) {
        message.success('Disable success')
        this.getData()
      } else {
        message.error(res.msg)
      }
    })
  }

  recoveryAdmin (record) {
    fetchPost(`/audit/auditor/status/save`, { status: 0, adminId: record.adminId }).then(res => {
      if (res.code === 0) {
        message.success('Restored')
        this.getData()
      } else {
        message.error(res.msg)
      }
    })
  }

  deleteAdmin (record) {
    fetchPost(`/audit/auditor/delete`, { adminId: record.adminId }).then(res => {
      if (res.code === 0) {
        message.success('Deleted success')
        this.getData()
      } else {
        message.error(res.msg)
      }
    })
  }

  render () {
    const { getFieldDecorator } = this.props.form
    let self = this
    let columns = [{
      title: 'Login account',
      dataIndex: 'account',
    },{
      title: 'Mobile',
      dataIndex: 'mobile',
    }, {
      title: 'Name',
      dataIndex: 'adminName',
    }, {
      title: 'Automatic daily order num',
      dataIndex: 'baseOrderNum',
      render: (text, record) => this.renderColumns(text, record, 'baseOrderNum'),
    }, {
      title: 'Manual daily order num',
      dataIndex: 'dailyManualOrderNum',
      render: (text, record) => this.renderColumns(text, record, 'dailyManualOrderNum'),
    }, {
      title: 'operation',
      dataIndex: 'operation',
      render: (text, record) => {
        const { editable } = record
        return (
          <div className="editable-row-operations">
            {
              editable ?
                <span>
                  <a onClick={() => this.save(record.key)}>Save</a>
                  <a style={{ marginLeft: 10 }} onClick={() => this.cancel(record.key)}>Cancel</a>
                </span>
                : <a onClick={() => this.edit(record.key)}>Edit</a>
            }
          </div>
        )
      },
    }, {
      title: 'Working state',
      render: (text, record) => {
        const { editable } = record
        return (
          <div>
            {
              record.status == 0 ?
                <Tag color="green">Working</Tag>
                :
                null
            }

            {
              record.status == 1 ?
                <Tag color="orange">On leave</Tag>
                : null
            }
          </div>
        )
      },
    }, {
      title: 'status',
      dataIndex: 'status',
      render: (text, record) => {
        const { editable } = record
        return (
          <div>
            {
              record.status === 1
                ? <span className={Style.forbiddenTip}>Disabled</span>
                : <Popconfirm title='Please confirm disabled this one?'
                              onConfirm={() => {
                                this.forbiddenAdmin(record)
                              }}
                              okText='Confirm' cancelText='Cancel'>
                  <a className='operateBtn' href='javascript:;'>Disable</a>
                </Popconfirm>
            }

            {
              record.status === 1 ? <a className='operateBtn'
                                       onClick={() => {
                                         this.recoveryAdmin(record)
                                       }} href='javascript:;'>Enable</a>
                : null
            }

            <Popconfirm title='Please confirm delete this one?'
                        onConfirm={() => {
                          this.deleteAdmin(record)
                        }}
                        okText='Confirm' cancelText='Cancel'>
              <a className='operateBtn' href='javascript:;'>Delete</a>
            </Popconfirm>
          </div>
        )
      },
    }
    ]

    const formItemLayout = {
      labelCol: {
        xs: { span: 8 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 16 },
        sm: { span: 16 },
      },
    }

    return (
      <div>
        <Modal
          title="Add Auditor"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText="Save"
        >

          <Form style={{ width: '100%', margin: 'auto' }} horizontal>
            <FormItem {...formItemLayout} label="adminId" style={{ display: 'none' }}>
              {getFieldDecorator('adminId', {})(
                <Input placeholder="required"/>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="Name">
              {getFieldDecorator('name', {
                rules: [
                  { required: true, message: 'Name is necessary!' },
                ],
              })(
                <Input placeholder="required"/>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="Mobile">
              {getFieldDecorator('mobile', {
                rules: [
                  { required: true, message: 'mobile is necessary!' },
                ],
              })(
                <Input placeholder="required"/>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="Caseload">
              {getFieldDecorator('baseOrderNum', {
                rules: [
                  { required: true, message: 'mobile is necessary!' },
                ],
              })(
                <Input placeholder="Daily Order Num"/>
              )}
            </FormItem>
          </Form>


        </Modal>

        <div className={Style.title}>
          <Icon className={Style.icon} type='tag-o'/>
          Auditor Manage
          <Button className='ml20' onClick={(e) => {
            this.showModal(e)
          }} type='primary'> New </Button>
        </div>

        <div>
          <Col span={20}>
            <Table pagination={this.setPagination()}
                   key='adminId'
                   rowKey='adminId'
                   bordered
                   dataSource={this.state.auditorList}
                   columns={columns}
                   loading={self.state.loading}
                   size='small'
            />
          </Col>
        </div>
      </div>
    )
  }
}

Index = Form.create()(Index)
export default Index
